﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using PanGu;
using PanGu.HighLight;
using WinnerCMS.BLL;
using WinnerCMS.Model;
using WinnerCMS.BLL.PageFactory;
namespace WinnerCMS.PlugIn.Indexer
{
    public class Search
    {
        private TimeSpan _duration;

        public PagingParam PagingParam { get; set; }

        private string KeyWord
        {
            get
            {
                return HttpContext.Current.Request.QueryString["K"];
            }
        }
        DirectoryInfo INDEX_DIR = new DirectoryInfo(CMSConfig.Instance().FullTextIndexPath);
        /// <summary>
        /// 组织搜索结果
        /// </summary>
        /// <returns></returns>
        public IList<Article> GetData()
        {
            DateTime start = DateTime.Now;


            IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(INDEX_DIR), true);
            PanGuAnalyzer analyzer = new PanGuAnalyzer();

            QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Content", analyzer);
            Query query = qp.Parse(this.KeyWord);
            var collector = TopScoreDocCollector.Create(PagingParam.PageNo * PagingParam.PageSize, false);
            //var sortFields = new SortField[2];
            //sortFields[1] = SortField.FIELD_SCORE;

            //Sort sort = new Sort(sortFields);

             searcher.Search(query,collector);

             ScoreDoc[] hits = collector.TopDocs(PagingParam.StartRecord, PagingParam.EndRecord).ScoreDocs;
             PagingParam.RecordCount = collector.TotalHits;

            //创建HTMLFormatter,参数为高亮单词的前后缀
            SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
            //创建Highlighter ，输入HTMLFormatter 和盘古分词对象Semgent
            Highlighter highlighter =  new Highlighter(simpleHtmlFormatter,  new Segment()) { FragmentSize = 200 };
            
         
            List<Article> list = new List<Article>();
            foreach (ScoreDoc sd in hits)
            {
                Document doc = searcher.Doc(sd.Doc);
                Console.WriteLine(doc.Get("body"));
                //获取最匹配的摘要段
                string content = highlighter.GetBestFragment(this.KeyWord, doc.Get("Content")).Trim();
                var model = new Article
                {
                    Id = int.Parse(doc.Get("ID")),
                    CategoryId = int.Parse(doc.Get("CategoryId")),
                    ContentTitle = doc.Get("ContentTitle"),
                    UpdateTime = DateTime.Parse(doc.Get("UpdateTime")),
                    TemplateFileName = doc.Get("TemplateFileName"),
                    Content = content,
                    Link = ""
                };

                list.Add(model);
            }

             
        

          
            searcher.Dispose();

            this._duration = DateTime.Now - start;

            foreach (var t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }

            return list;
        }

      

        /// <summary>
        /// Prepares the string with seach summary information.
        /// </summary>
        public string Summary
        {
            get
            {
                if (this.PagingParam.RecordCount > 0)
                    return string.Concat("查询到符合“", this.KeyWord, "”的", this.PagingParam.RecordCount, "项， 以下是第<b>", (this.PagingParam.StartRecord), " - ", this.PagingParam.EndRecord, "</b> 项 . (搜索用时", this._duration.TotalSeconds, " 秒)");
                return "查找不到结果";
            }
        }
    }
}